package com.cos.shop.web.controller;

import com.alibaba.fastjson.JSON;
import com.cos.shop.common.Const;
import com.cos.shop.common.ResponseCode;
import com.cos.shop.common.ResponseResult;
import com.cos.shop.entity.User;
import com.cos.shop.services.CartServices;
import com.cos.shop.services.impl.CartServicesImpl;
import com.cos.shop.util.PageHelper;
import com.cos.shop.util.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: COS
 * @time: 2023/5/11 11:31
 * @description:
 */
@WebServlet("/cart")
public class CartController extends BaseServlet {
    private CartServices cs = new CartServicesImpl();

    public String updateCartNum(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute(Const.LOGIN_INFO);
        //获取pid num
        int pid = StringUtils.stringToInt(request.getParameter("pid"));
        int num = StringUtils.stringToInt(request.getParameter("num"));
        //访问业务层进行数据操作
        ResponseResult rr = cs.changeCart(user.getUid(),pid,num);
        //不需要结果直接重定向 获取购物车页面数据局
        // return Const.REDIRECT+"/getCart";
        String s = JSON.toJSONString(rr);
        return s;
    }

    public String clearCart(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute(Const.LOGIN_INFO);
        //获取数据
        int pid = StringUtils.stringToInt(request.getParameter("pid"));
        //访问业务层处理删除操作
        ResponseResult rr = cs.clearCart(pid, user.getUid());
        request.setAttribute(Const.MSG, rr);
        return Const.MESSAGE;
    }

    public String getCart(HttpServletRequest request, HttpServletResponse response) {
        User user = (User) request.getSession().getAttribute(Const.LOGIN_INFO);
        // 发送请求给业务层 处理购物车数据查询
        ResponseResult rr = cs.getCartWithProByUid(user.getUid());
        // 转发
        request.setAttribute("rr", rr);
        return Const.FORWARD + "cart.jsp";
    }

    public String addCart(HttpServletRequest request, HttpServletResponse response) {
        //判断用户是否等了
        User user = (User) request.getSession().getAttribute(Const.LOGIN_INFO);
        //接受数据
        int goodsId = StringUtils.stringToInt(request.getParameter("goodsId"));
        //访问业务层操作新增购物车
        ResponseResult rr = cs.addCart(user.getUid(), goodsId);
        if (rr.getCode() == ResponseCode.SUCCESS.getCode()) {
            return Const.REDIRECT + "cartSuccess.jsp";
        }
        request.setAttribute("msg", rr);
        return Const.MESSAGE;
    }
}
